package org.algorithm.floyd;

import java.util.Arrays;

public class FloydAlgorithm {
    public static void main(String[] args) {
        // 测试看看图是否创建成功
        char[] vertex = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        //创建邻接矩阵
        int[][] matrix = new int[vertex.length][vertex.length];
        final int N = 65535;
        matrix[0] = new int[]{0, 5, 7, N, N, N, 2};
        matrix[1] = new int[]{5, 0, N, 9, N, N, 3};
        matrix[2] = new int[]{7, N, 0, N, 8, N, N};
        matrix[3] = new int[]{N, 9, N, 0, N, 4, N};
        matrix[4] = new int[]{N, N, 8, N, 0, 5, 4};
        matrix[5] = new int[]{N, N, N, 4, 5, 0, 6};
        matrix[6] = new int[]{2, 3, N, N, 4, 6, 0};

        //创建 Graph 对象
        Graph graph = new Graph(vertex, matrix);
        //调用弗洛伊德算法
       graph.floyd();
        graph.show();
    }


}

class Graph {
    private char[] vertex;
    private int[][] matrix;
    private int[][] preVertex;

    public Graph(char[] vertex, int[][] matrix) {
        this.vertex = vertex;
        this.matrix = matrix;
        this.preVertex = new int[vertex.length][vertex.length];

        for (int i = 0; i < vertex.length; i++) {
            Arrays.fill(preVertex[i], i);
        }
    }

    public void floyd() {
        int len;

        //遍历以中间节点相连接的所有可能边
        for (int k = 0; k < vertex.length; k++) {

            for (int i = 0; i < vertex.length; i++) {

                for (int j = 0; j < vertex.length; j++) {
                    len = matrix[k][j] + matrix[k][i];
                    if (len < matrix[i][j]) {
                        matrix[i][j] = len;
                        preVertex[i][j] = preVertex[k][j];
                    }
                }
            }
        }
    }


    public void show() {

        //为了显示便于阅读，我们优化一下输出
        char[] vertex = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
        for (int k = 0; k < matrix.length; k++) {
            // 先将pre数组输出的一行
            for (int i = 0; i < matrix.length; i++) {
                System.out.print(vertex[preVertex[k][i]] + " ");
            }
            System.out.println();
            // 输出dis数组的一行数据
            for (int i = 0; i < matrix.length; i++) {
                System.out.print("("+vertex[k]+"到"+vertex[i]+"的最短路径是" + matrix[k][i] + ") ");
            }
            System.out.println();

        }

    }
}
